<template>
  <view class="uni-container">
    <uni-forms
      ref="form"
      :model="formData"
      validateTrigger="bind"
      label-width="120px"
    >
      <uni-forms-item
        name="user_id"
        label="优惠券所属用户ID"
        v-if="isSuperAdmin"
        required
      >
        <uni-easyinput
          placeholder="优惠券所属用户ID，参考uni-id-users表"
          :disabled="true"
          v-model="formData.user_id"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="category_id" label="优惠券所属活动" required>
        <uni-data-picker
          v-model="formData.category_id"
          collection="news-articles-image"
          field="title as text, _id as value"
          class="custom-picker"
          :where="titleFormat"
          :key="titleFormat"
          @change="onCategoryChange"
        ></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="name" label="优惠券名称" required>
        <uni-easyinput
          placeholder="优惠券名称"
          v-model="formData.name"
          trim="both"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="discount" label="折扣率" required>
        <uni-data-select
          v-model="formData.discount"
          :localdata="formOptions.discount_data"
          placeholder="请选择折扣率"
        ></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="validity" label="有效期" required>
        <uni-datetime-picker
          v-model="formData.validity"
          type="time"
          :clear-icon="false"
          return-type="timestamp"
          placeholder="请选择优惠券有效期"
        ></uni-datetime-picker>
        <text class="tips-text"
          >优惠券的有效期自动设置为活动结束当天晚上的12点</text
        >
      </uni-forms-item>
      <uni-forms-item name="status" label="优惠券状态">
        <uni-data-checkbox
          v-model="formData.status"
          :localdata="formOptions.status_localdata"
        ></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="customImage" label="自定义图片">
        <uni-file-picker
          v-model="formData.customImage"
          fileMediatype="image"
          :auto-upload="true"
          return-type="object"
        ></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="create_date" label="创建时间">
        <uni-datetime-picker
          return-type="timestamp"
          v-model="formData.create_date"
        ></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="last_modify_date" label="最后修改时间">
        <uni-datetime-picker
          return-type="timestamp"
          v-model="formData.last_modify_date"
        ></uni-datetime-picker>
      </uni-forms-item>
      <view class="uni-button-group">
        <button
          type="primary"
          class="uni-button"
          style="width: 100px"
          @click="submit"
        >
          提交
        </button>
        <button
          class="uni-button"
          style="width: 100px; margin-left: 15px"
          @click="goBack"
        >
          返回
        </button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { validator } from "@/js_sdk/validator/coupons.js";
import { store } from "@/uni_modules/uni-id-pages/common/store";

// const db = uniCloud.database();
// const dbCmd = db.command;
// const dbCollectionName = 'coupons';

function getValidator(fields) {
  let result = {};
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key];
    }
  }
  return result;
}

function numberRange(start, end) {
  return Array.from({ length: end - start + 1 }, (_, i) => ({
    value: start + i,
    text: `${start + i}折`,
  }));
}

export default {
  data() {
    let formData = {
      category_id: "",
      user_id: "",
      name: "",
      discount: null,
      validity: "",
      status: 0,
      customImage: null,
      create_date: null,
      last_modify_date: null,
    };
    return {
      originFormData: null,
      formData,
      titleFormat: "", // 将在 onLoad 中动态设置
      formDataId: "",
      formOptions: {
        discount_data: numberRange(1, 99),
        status_localdata: [
          {
            value: 0,
            text: "未发布",
          },
          {
            value: 1,
            text: "已发布",
          },
          {
            value: 2,
            text: "已过期",
          },
        ],
      },
      rules: {
        ...getValidator(Object.keys(formData)),
      },
    };
  },

  onLoad(e) {
    if (e.id) {
      this.formDataId = e.id;
      this.getDetail(e.id);
    }

    // 设置活动过滤条件
    if (this.$hasRole("admin")) {
      this.titleFormat = 'title != null && title != ""';
    } else {
      const userId = store.userInfo._id;
      this.titleFormat = `title != null && title != \"\" && user_id == '${userId}'`;
    }
  },

  onReady() {
    this.$refs.form.setRules(this.rules);
  },

  computed: {
    isSuperAdmin() {
      return this.$hasRole("admin");
    },
  },

  methods: {
    async onCategoryChange(e) {
      const articleId = e.detail.value[0].value;
      // console.log('选择的活动：', articleId)

      try {
        // 使用 uniCloud 查询活动详情
        const db = uniCloud.database();
        const res = await db
          .collection("news-articles-image")
          .doc(articleId)
          .field("end_time")
          .get();

        if (res.result.data && res.result.data.length > 0) {
          const endTime = res.result.data[0].end_time;
          const endDate = new Date(endTime);
          // 设置为当天的 23:59:59.999
          endDate.setHours(23, 59, 59, 999);
          // console.log('优惠券结束时间：', endDate.toLocaleString())

          // 可以在这里设置优惠券的有效期
          this.formData.validity = endDate.getTime();
        }
      } catch (err) {
        console.error("获取活动结束时间失败：", err);
        uni.showToast({
          title: "获取活动信息失败",
          icon: "none",
        });
      }
    },
    /**
     * 比较表单数据是否有变化
     * @param {Object} newData - 新的表单数据
     * @param {Object} oldData - 原始表单数据
     * @returns {Boolean} - 如果数据有变化返回true，否则返回false
     */
    compareData(newData, oldData) {
      const compareKeys = [
        "user_id",
        "category_id",
        "name",
        "discount",
        "validity",
        "status",
        "customImage",
        "create_date",
        "last_modify_date",
      ];
      let hasChanged = false;

      for (const key of compareKeys) {
        // 处理 customImage 字段
        if (key === "customImage") {
          const newUrl = newData[key]?.url || newData[key] || "";
          const oldUrl = oldData[key]?.url || oldData[key] || "";
          if (newUrl !== oldUrl) {
            // console.log('图片URL发生变化');
            hasChanged = true;
            break;
          }
          continue;
        }

        // 处理日期字段
        if (key === "create_date" || key === "last_modify_date") {
          const newDate = newData[key]
            ? new Date(newData[key]).getTime()
            : null;
          const oldDate = oldData[key]
            ? new Date(oldData[key]).getTime()
            : null;
          if (newDate !== oldDate) {
            // console.log('日期字段发生变化');
            hasChanged = true;
            break;
          }
          continue;
        }

        // 处理其他字段
        // 新的值不等于原始值且新的字段不是 user_id
        // 新的值的user_id是不能修改的，这里不需要比较
        if (newData[key] !== oldData[key] && key !== "user_id") {
          // 如果两个值都是 null 或 undefined，认为它们相等
          if (newData[key] == null && oldData[key] == null) {
            continue;
          }
          // console.log('其他字段发生变化', key, newData[key], oldData[key]);
          hasChanged = true;
          break;
        }
      }

      return hasChanged;
    },
    goBack() {
      this.getOpenerEventChannel().emit("refreshData");
      setTimeout(() => uni.navigateBack(), 500);
    },
    /**
     * 获取表单数据
     */
    async getDetail(id) {
      try {
        const couponManager = uniCloud.importObject("coupon-manager", {
          customUI: true,
        });
        const res = await couponManager.getCoupon(id);

        if (res.code === 200 && res.data) {
          // 处理图片数据格式
          if (res.data.customImage) {
            res.data.customImage = { url: res.data.customImage };
          }
          this.formData = { ...res.data };
          this.originFormData = { ...res.data };
        } else {
          uni.showModal({
            content: res.message || "获取数据失败",
            showCancel: false,
          });
        }
      } catch (err) {
        uni.showModal({
          content: err.message || "请求服务失败",
          showCancel: false,
        });
      }
    },

    /**
     * 验证表单并提交
     */
    submit() {
      uni.showLoading({
        mask: true,
      });
      this.$refs.form
        .validate()
        .then((res) => {
          return this.submitForm(res);
        })
        .catch(() => {})
        .finally(() => {
          uni.hideLoading();
        });
    },

    /**
     * 提交表单
     */
    async submitForm(value) {
      try {
        // 处理图片数据格式
        const submitData = { ...value };
        if (submitData.customImage && submitData.customImage.url) {
          submitData.customImage = submitData.customImage.url;
        }

        // 比较数据是否有变化
        if (!this.compareData(submitData, this.originFormData)) {
          console.log("数据未发生变化");
          uni.showToast({
            title: "数据未发生变化",
            icon: "none",
          });
          return false;
        }

        const couponManager = uniCloud.importObject("coupon-manager");
        const res = await couponManager.updateCoupon(this.formDataId, value);

        if (res.code === 200) {
          uni.showToast({
            title: "修改成功",
          });
          this.getOpenerEventChannel().emit("refreshData");
          setTimeout(() => uni.navigateBack(), 500);
        } else {
          uni.showModal({
            content: res.message || "修改失败",
            showCancel: false,
          });
        }
      } catch (err) {
        uni.showModal({
          content: err.message || "请求服务失败",
          showCancel: false,
        });
      }
    },
  },
};
</script>

<style>
.custom-picker :deep(.uni-select--mask) {
  max-height: 300px !important;
  overflow-y: auto !important;
}

.custom-picker :deep(.uni-select__selector) {
  max-height: 300px !important;
  overflow-y: auto !important;
}

.tips-text {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  display: block;
}
</style>
